package com.lqq.chapter06;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * @Author lqq677
 * @Date 2021/8/11 18:10
 * @Description 使用Callable 和Future
 */
public class CallableDemo {

    //实现Runnable接口
    static class MyRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+"线程进入了run方法");
        }
    }

    //实现Callable接口
    static class MyCallable implements Callable {

        @Override
        public Long call() throws Exception {
              try {
                  System.out.println(Thread.currentThread().getName()+"线程进入了call方法，开始准备睡觉");
                  Thread.sleep(1000);
                  System.out.println(Thread.currentThread().getName()+"睡醒了");
              }catch (Exception e){
                          e.printStackTrace();
                      }
              return System.currentTimeMillis();
        }
    }

    public static void main(String[] args) throws Exception {

        //声明Runnable
        Runnable runnable = new MyRunnable();

        //声明Callable
        Callable callable = new MyCallable();

        FutureTask<Long> task = new FutureTask(callable);

        //线程二
        new Thread(task, "线程二").start();
        for (int i = 0; i < 10; i++) {
            Long result = task.get();
            System.out.println(result);
        }

        //线程一
        new Thread(runnable,"线程一").start();
    }
}
